package util;

import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


public class FileUtil {


    // 读取synonyms.txt
    static Map<String, String> map;

    /**
     * 敏感词集合
     */
    static Set<String> sensitiveSet;

//    static {
//        readSensitiveWords(); // 读取敏感词
//        readSynonym(); // 读取机构同义词，如：“北航”、“北京航空航天大学”
//    }


    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);

        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }


    /**
     * 读取同义词
     */
    private static void readSynonym() {
        try {
            map = new HashMap<String, String>();
            // System.out.println("path is: "+FileUtil.class.getResource("/"));
            String synonymsPath = FileUtil.class.getResource("/synonyms.txt").getPath();
            synonymsPath = URLDecoder.decode(synonymsPath, "UTF-8");
            // System.out.println("path: "+synonymsPath);
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(synonymsPath), "UTF-8"));
            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                String pri = line.split(",")[0]; // 原词
                String abb = line.split(",")[1]; // 缩写词
                if (pri.length() < abb.length()) { // 有时原词和缩写词会颠倒位置
                    String temp = pri;
                    pri = abb;
                    abb = temp;
                }
                map.put(abb, pri);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取敏感词
     */
    private static void readSensitiveWords() {
        try {
            sensitiveSet = new HashSet<>();
            String synonymsPath = FileUtil.class.getResource("/minganci.txt").getPath();
            synonymsPath = URLDecoder.decode(synonymsPath, "UTF-8");
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(synonymsPath), "UTF-8"));
            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (!line.equals("")) {
                    sensitiveSet.add(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到包含近义词的映射
     */
    public static Map<String, String> getSynonymMap() {
        return map;
    }

    /**
     * 判断输入是否包含敏感词
     *
     * @param input 可能是空格隔开的多个词
     * @return
     */
    public static boolean isContainSensitiveWords(String input) {
        if (input == null) return false;
        String[] arr = input.split(" ");
        for (String str : arr) {
            if (sensitiveSet.contains(str)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断输入是否包含敏感词
     *
     * @param inputArr 字符串数组
     * @return
     */
    public static boolean isContainSensitiveWords(String[] inputArr) {
        if (inputArr == null) return false;
//        String[] arr = input.split(" ");
        for (String str : inputArr) {
            if (sensitiveSet.contains(str)) {
                System.out.println("发现敏感词：" + str);
                return true;
            }
        }
        return false;
    }


    /**
     * 得到当前机构的近义词（如：输入“北航”，输出“北京航空航天大学”）;若输入为null，则输出为null
     */
    public static String getSynonym(String org) {
        if (org == null) {
            return null;
        }
        org = org.trim();
        if (map.containsKey(org)) {
            return map.get(org);
        }
        return org;
    }

    /**
     * 将一个String数组拼接成一个字符串，用空格分隔
     */
    public String changeStr(String[] arr) {
        int num = arr.length;
        String result = null;
        for (int i = 0; i < num; i++) {
            if (result == null) {
                result = arr[i];
            } else {
                result = result + " " + arr[i];
            }
        }
        if (result == null) {
            result = "";
        }
        return result;
    }

    /**
     * 文件输出
     *
     * @param path     输出文件路径
     * @param isAppend 是否拼接，若为true，则拼接；若为false，则覆盖
     */
    public static BufferedWriter initBufferedWriter(String path, boolean isAppend) {
        OutputStreamWriter osw = null;
        BufferedWriter bos = null;
        try {
            osw = new OutputStreamWriter(new FileOutputStream(new File(path),
                    isAppend), "utf-8");
            bos = new BufferedWriter(osw);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bos;
    }

    /**
     * 文件输出（若已有同名文件，则覆盖）
     * @param path     输出文件路径
     */
    public static BufferedWriter initBufferedWriter(String path) {
        BufferedWriter bos = initBufferedWriter(path, false);
        return bos;
    }

    public static void main(String[] args) {
        System.out.println(FileUtil.getSynonym("北京航空航天大学"));
    }

}
